import {Button, Upload} from "antd"
import {useEffect, useState} from "react";
import {UploadOutlined} from "@ant-design/icons";
import {BASE_URL} from "@utils/constants.js";

export default (props) => {
    const {value, onChange, max = 1} = props;
    const [fileList, setFileList] = useState([]);


    useEffect(() => {
        if (!value) return
        if (max > 1) {
            setFileList(value.map((item, index) => {
                let url = BASE_URL + item;
                if (item.startsWith('http')) url = item;
                return {
                    uid: index,
                    name: item?.split('/')?.pop(),
                    status: 'done',
                    ur,
                }
            }))
        } else if (max === 1) {
            let url = BASE_URL + value;
            if (value?.startsWith('http')) url = value;
            setFileList([{
                uid: '-1',
                name: value?.split('/')?.pop(),
                status: 'done',
                url
            }]);
        }
    }, []);
    return (
        <>
            <Upload
                action={`${BASE_URL}file/upload`}
                headers={{
                    token: localStorage.getItem('token') || '',
                }}
                fileList={fileList}
                onChange={(e) => {
                    if (e.file?.response?.code?.value === 200) {
                        let item = e.fileList.find((item) => item.uid === e.file.uid)
                        if (item) item.url = e.file.response.body.path
                    }
                    setFileList(e.fileList)
                    if (max > 1) {
                        onChange(e.fileList.map((item) => item.url))
                    } else {
                        onChange(e.fileList[0]?.url)
                    }
                }}
            >
                {fileList.length >= max ? null : (<div>
                    <Button icon={<UploadOutlined/>}>上传</Button>
                </div>)
                }
            </Upload>
        </>
    )
}